import {
  getUserId,
  getUserName,
  getUserStatus,
  setToken,
  setUserId,
  setUserName,
  setUserRoles,
  setUserStatus
} from '@/libs/auth'
import deepClone from '@/libs/deepClone'
import type { ActionContext } from 'vuex'
import { getUserRoles } from '@/libs/auth'
import router from '@/router'
import { RouteRecordRaw } from 'vue-router'
import asyncRouters from '@/router/asyncRouters'
import { clearStorage } from '@/libs/localstoreage'
import { RootState } from '..'
import { mLogin } from '@/api/login'
import { notification } from 'ant-design-vue'
import { message } from '@/libs/global/antDesignVue'

export type LoginState = {
  roles: null | number[]
  platFormUserName: string | null
  platFormUserId: string | null
  token: string | null
}
export type LoginContext = ActionContext<LoginState, RootState>

export const state: LoginState = {
  roles: null,
  platFormUserName: null,
  platFormUserId: null,
  token: null
}
export const getters = {
  GETROLES(state: LoginState) {
    return state.roles
  },
  GETPLATFORMUSERID(state: LoginState) {
    return state.platFormUserId
  },
  GETPLATFORMUSERNAME(state: LoginState) {
    return state.platFormUserName
  },
  GETTOKEN(state: LoginState) {
    return state.token
  }
}
export const mutations = {
  SETUSERINFO_ROLES(state: LoginState, data: number[]) {
    state.roles = data
    setUserRoles(data)
  },
  SETUSERINFO_TOKEN(state: LoginState, data: string) {
    state.token = data
    setToken(data)
  },
  SETUSERINFO_USERNAME(state: LoginState, data: string) {
    state.platFormUserName = data
    setUserName(data)
  },
  SETUSERINFO_USERID(state: LoginState, data: string) {
    state.platFormUserId = data
    setUserId(data)
  }
}

export const actions = {
  LOGIN(
    { commit, dispatch }: LoginContext,
    data: { platFormUserName: string; platFormUserPass: string }
  ) {
    return new Promise(async (rep, rej) => {
      console.log('校验');

      if (!data.platFormUserName) return rej('请输入账号')
      if (!data.platFormUserPass) return rej('请输入密码')
      /**登录接口调用 */
      let res = await mLogin(data).catch(err => { })
      if (!res) return rej(false)

      // 存储用户信息
      commit('SETUSERINFO_USERNAME', res.data.platFormUserName)
      commit('SETUSERINFO_USERID', res.data.platFormUserId)
      commit('SETUSERINFO_ROLES', [1])

      // 登录完成后加载路由
      dispatch('GenerateRoutes')
        .then(res => {
          rep(true)
        })
        .catch(err => {
          console.log('路由信息加载失败', err)
          rej(false)
        })
    })
  },
  LOGOUT({ commit, dispatch }: LoginContext) {
    return new Promise(async (rep, rej) => {
      clearStorage()
      location.reload()
    })
  },
  /**获取用户信息 本地缓存没有返会错误 */
  GetUserInfo: ({ state, commit, rootGetters }: LoginContext): Promise<{ roles: number[] }> => {
    return new Promise((rep, rej) => {
      try {
        let userRoles = getUserRoles()
        let userId = getUserId()
        let userName = getUserName()
        commit('SETUSERINFO_ROLES', userRoles)
        commit('SETUSERINFO_USERNAME', userName)
        commit('SETUSERINFO_USERID', userId)
        rep({ roles: userRoles })
      } catch (err) {
        console.error('getuserinfo error place check', err)

        rej(false)
      }
    })
  },
  /**筛选需要的路由 */
  GenerateRoutes: ({ commit, dispatch }: LoginContext) => {
    return new Promise<void>(async (resolve, reject) => {
      try {
        let routers = deepClone(asyncRouters)
        routers.map((data: RouteRecordRaw) => {
          router.addRoute(data.name || data.path.replace('/', '-').substring(1), data)
        })
        console.log('路由加载完成', router.getRoutes())
        resolve()
      } catch (err) {
        console.log('路由信息加载失败', err)
        dispatch('LOGOUT').then(res => {
          reject(false)
        })
      }
    })
  }
}
export default {
  namespaced: true, // 声明命名空间
  state,
  mutations,
  actions,
  getters
}
